package org.jeecg.modules.oms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.oms.entity.OmsInquiryRule;
import org.jeecg.modules.oms.entity.OmsInquiryRuleValue;
import org.jeecg.modules.oms.service.IOmsInquiryRuleService;
import org.jeecg.modules.oms.service.IOmsInquiryRuleValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 询单规则管理
 */
@Api(tags = "询单规则管理")
@RestController
@RequestMapping("/oms/inquiry/rule")
@Slf4j
public class OmsInquiryRuleController extends JeecgController<OmsInquiryRule, IOmsInquiryRuleService> {

    @Autowired
    private IOmsInquiryRuleService inquiryRuleService;

    @Autowired
    private IOmsInquiryRuleValueService inquiryRuleValueService;

    /**
     * 分页列表查询
     *
     * @param omsInquiryRule 查询条件
     * @param pageNo 页码
     * @param pageSize 页大小
     * @param req 请求对象
     * @return 分页结果
     */
    @AutoLog(value = "询单规则-分页列表查询")
    @ApiOperation(value = "询单规则-分页列表查询", notes = "询单规则-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<OmsInquiryRule>> queryPageList(OmsInquiryRule omsInquiryRule,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                       HttpServletRequest req) {
        Page<OmsInquiryRule> page = new Page<>(pageNo, pageSize);
        IPage<OmsInquiryRule> pageList = inquiryRuleService.getInquiryRulePageList(page, 
                omsInquiryRule.getName(), omsInquiryRule.getType(), omsInquiryRule.getEnabled());
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param requestBody 请求体，包含规则信息和规则值
     * @return 添加结果
     */
    @AutoLog(value = "询单规则-添加")
    @ApiOperation(value = "询单规则-添加", notes = "询单规则-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody Map<String, Object> requestBody) {
        try {
            OmsInquiryRule rule = new OmsInquiryRule();
            rule.setName((String) requestBody.get("name"));
            
            // 安全的类型转换
            Object typeObj = requestBody.get("type");
            rule.setType(typeObj instanceof String ? Integer.parseInt((String) typeObj) : (Integer) typeObj);
            
            Object isMustObj = requestBody.get("isMust");
            rule.setIsMust(isMustObj instanceof String ? Integer.parseInt((String) isMustObj) : (Integer) isMustObj);
            
            Object sortNoObj = requestBody.get("sortNo");
            rule.setSortNo(sortNoObj instanceof String ? Integer.parseInt((String) sortNoObj) : (Integer) sortNoObj);
            
            rule.setRemark((String) requestBody.get("remark"));

            @SuppressWarnings("unchecked")
            List<String> values = (List<String>) requestBody.get("values");

            boolean success = inquiryRuleService.saveRuleWithValues(rule, values);
            if (success) {
                return Result.OK("添加成功！");
            } else {
                return Result.error("添加失败！");
            }
        } catch (Exception e) {
            log.error("添加询单规则失败", e);
            return Result.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 编辑
     *
     * @param requestBody 请求体，包含规则信息和规则值
     * @return 编辑结果
     */
    @AutoLog(value = "询单规则-编辑")
    @ApiOperation(value = "询单规则-编辑", notes = "询单规则-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody Map<String, Object> requestBody) {
        try {
            OmsInquiryRule rule = new OmsInquiryRule();
            rule.setId((String) requestBody.get("id"));
            rule.setName((String) requestBody.get("name"));
            
            // 安全的类型转换
            Object typeObj = requestBody.get("type");
            rule.setType(typeObj instanceof String ? Integer.parseInt((String) typeObj) : (Integer) typeObj);
            
            Object isMustObj = requestBody.get("isMust");
            rule.setIsMust(isMustObj instanceof String ? Integer.parseInt((String) isMustObj) : (Integer) isMustObj);
            
            Object sortNoObj = requestBody.get("sortNo");
            rule.setSortNo(sortNoObj instanceof String ? Integer.parseInt((String) sortNoObj) : (Integer) sortNoObj);
            
            rule.setRemark((String) requestBody.get("remark"));

            @SuppressWarnings("unchecked")
            List<String> values = (List<String>) requestBody.get("values");

            boolean success = inquiryRuleService.saveRuleWithValues(rule, values);
            if (success) {
                return Result.OK("编辑成功!");
            } else {
                return Result.error("编辑失败！");
            }
        } catch (Exception e) {
            log.error("编辑询单规则失败", e);
            return Result.error("编辑失败：" + e.getMessage());
        }
    }

    /**
     * 通过id删除
     *
     * @param id 规则ID
     * @return 删除结果
     */
    @AutoLog(value = "询单规则-通过id删除")
    @ApiOperation(value = "询单规则-通过id删除", notes = "询单规则-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            boolean success = inquiryRuleService.deleteRuleWithValues(id);
            if (success) {
                return Result.OK("删除成功!");
            } else {
                return Result.error("删除失败！");
            }
        } catch (Exception e) {
            log.error("删除询单规则失败", e);
            return Result.error("删除失败：" + e.getMessage());
        }
    }

    /**
     * 批量删除
     *
     * @param ids 规则ID列表，逗号分隔
     * @return 删除结果
     */
    @AutoLog(value = "询单规则-批量删除")
    @ApiOperation(value = "询单规则-批量删除", notes = "询单规则-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        try {
            String[] idArray = ids.split(",");
            for (String id : idArray) {
                inquiryRuleService.deleteRuleWithValues(id.trim());
            }
            return Result.OK("批量删除成功!");
        } catch (Exception e) {
            log.error("批量删除询单规则失败", e);
            return Result.error("批量删除失败：" + e.getMessage());
        }
    }

    /**
     * 通过id查询
     *
     * @param id 规则ID
     * @return 规则详情
     */
    @AutoLog(value = "询单规则-通过id查询")
    @ApiOperation(value = "询单规则-通过id查询", notes = "询单规则-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<Map<String, Object>> queryById(@RequestParam(name = "id", required = true) String id) {
        try {
            OmsInquiryRule rule = inquiryRuleService.getById(id);
            List<OmsInquiryRuleValue> values = inquiryRuleValueService.getValuesByRuleId(id);
            
            Map<String, Object> result = new java.util.HashMap<>();
            result.put("rule", rule);
            result.put("values", values);
            
            return Result.OK(result);
        } catch (Exception e) {
            log.error("查询询单规则详情失败", e);
            return Result.error("查询失败：" + e.getMessage());
        }
    }

    /**
     * 更新启用状态
     *
     * @param id 规则ID
     * @param enabled 启用状态
     * @return 更新结果
     */
    @AutoLog(value = "询单规则-更新启用状态")
    @ApiOperation(value = "询单规则-更新启用状态", notes = "询单规则-更新启用状态")
    @PostMapping(value = "/updateEnabled")
    public Result<String> updateEnabled(@RequestParam(name = "id", required = true) String id,
                                       @RequestParam(name = "enabled", required = true) Integer enabled) {
        try {
            boolean success = inquiryRuleService.updateEnabledStatus(id, enabled);
            if (success) {
                return Result.OK("更新成功!");
            } else {
                return Result.error("更新失败！");
            }
        } catch (Exception e) {
            log.error("更新询单规则启用状态失败", e);
            return Result.error("更新失败：" + e.getMessage());
        }
    }

    /**
     * 根据门类型获取启用的规则列表
     *
     * @param type 门类型
     * @return 规则列表
     */
    @AutoLog(value = "询单规则-根据门类型获取启用规则")
    @ApiOperation(value = "询单规则-根据门类型获取启用规则", notes = "询单规则-根据门类型获取启用规则")
    @GetMapping(value = "/getEnabledRules")
    public Result<List<OmsInquiryRule>> getEnabledRules(@RequestParam(name = "type", required = false) Integer type) {
        try {
            List<OmsInquiryRule> rules = inquiryRuleService.getEnabledRulesByType(type);
            return Result.OK(rules);
        } catch (Exception e) {
            log.error("获取启用规则列表失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 获取规则值列表
     *
     * @param ruleId 规则ID
     * @return 规则值列表
     */
    @AutoLog(value = "询单规则-获取规则值列表")
    @ApiOperation(value = "询单规则-获取规则值列表", notes = "询单规则-获取规则值列表")
    @GetMapping(value = "/getValues")
    public Result<List<OmsInquiryRuleValue>> getValues(@RequestParam(name = "ruleId", required = true) String ruleId) {
        try {
            List<OmsInquiryRuleValue> values = inquiryRuleValueService.getValuesByRuleId(ruleId);
            return Result.OK(values);
        } catch (Exception e) {
            log.error("获取规则值列表失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 根据门类型获取规则列表
     *
     * @param type 门类型
     * @return 规则列表
     */
    @AutoLog(value = "询单规则-根据门类型获取规则列表")
    @ApiOperation(value = "询单规则-根据门类型获取规则列表", notes = "询单规则-根据门类型获取规则列表")
    @GetMapping(value = "/listByType")
    public Result<List<OmsInquiryRule>> listByType(@RequestParam(name = "type") Integer type) {
        try {
            QueryWrapper<OmsInquiryRule> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("type", type);
            queryWrapper.eq("enabled", 1);
            queryWrapper.orderByAsc("sort_no");
            List<OmsInquiryRule> list = inquiryRuleService.list(queryWrapper);
            return Result.OK(list);
        } catch (Exception e) {
            log.error("根据门类型获取规则列表失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }
}
